package com.yesido.javabase.concurrent;

/**
 * @author yesido
 * @description
 * @date 2023-07-05 20:55
 * @Version 8.3
 */
public class TestThreadLocal {
    //线程本地存储变量
    private static final ThreadLocal<Integer> THREAD_LOCAL_NUM = ThreadLocal.withInitial(() -> 0);

    public static void main(String[]
                                    args) {
        for (int i = 0; i < 3; i++) {//启动三个线程
           /* Thread t = new Thread() {
                @Override
                public void run() {
                    add10ByThreadLocal();
                }
            };*/

            Thread t = new Thread(() -> {
                add10ByThreadLocal();
            });
            t.start();
        }
    }

    /**
     * *线程本地
     * 存储变量加5
     */
    private static void add10ByThreadLocal() {
        for (int i = 0; i < 5; i++) {
            Integer n = THREAD_LOCAL_NUM.get();
            n += 1;
            THREAD_LOCAL_NUM.set(n);
            System.out.println(Thread.currentThread().getName() + ":ThreadLocalnum=" + n);
        }
    }
}
